import random
import secrets
from urllib.parse import quote_plus

import requests
from requests.auth import HTTPBasicAuth

domains = (
    'dt-vpn.top',
    # 'mimail.life',
    # 'vip-mail.world'
)
ADMIN_PSW = 'TxFEv0zzqmObrNQ6'
EMAIL_PSW = 'shuyuan008'


def create_box(email_name=None, email_psw=EMAIL_PSW, domain=None):
    if domain is None:
        domain = random.choice(domains)

    # if email_name is None, random tokens will be generated.
    if email_name is None:
        email_name = secrets.token_urlsafe(8)

    email = f'{email_name}@{domain}'
    auth = HTTPBasicAuth(f'admin@{domain}', ADMIN_PSW)
    body = {
        'name': email_name,
        'email': email,
        'passwordPlaintext': email_psw,
        'disabled': False,
        'superAdmin': False,
    }

    r = requests.post(f'https://mail.{domain}/admin/api/v1/boxes', auth=auth, json=body, verify=False, timeout=30)
    # print(r.status_code, r.text)
    if r.status_code == 201:
        email = email.lower()
        print(f'Email {email}:{email_psw} created.')
        return email
    else:
        print(f'Email create failed.')
    return None


def delete_box(email):
    domain = email.split('@')[-1]
    auth = HTTPBasicAuth(f'admin@{domain}', ADMIN_PSW)
    r = requests.delete(f'https://mail.{domain}/admin/api/v1/boxes/{quote_plus(email)}', auth=auth, timeout=30)
    # print(r.status_code, r.text)
    if r.status_code == 204:
        print(f'Email {email} deleted.')
    else:
        print(f'Email delete failed.')


if __name__ == '__main__':
    create_box(domain='dt-vpn.top')
    # delete_box('mikejames2@dt-vpn.top')